package com.example.wificov;


import java.util.List;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.view.*;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.widget.*;
import android.view.Menu;
import com.example.database.myDBHelper;
import com.example.wificovv2.R;
import com.example.wificovv2.WSTActivity;

public class Innitialvaluepic extends Activity {
		//Bat dau khoi tao database
		myDBHelper db;
		
	  	//Các biến 
		float ratio1, ratio2, xinnitial, yinnitial;
		int imgwidth, imgheight;
		int pos;
		String index;
		Resources res;		
		int APID, mapId;	
		int idAP ;
		String nameAP;
		
		//Các đối tượng tương tác
		
		ListView listApIn;
		private EditText apnameinnitial, xposition, yposition, radius, angle;
		private Button btn_calculate, btn_plansave, btn_marker, btn_next;		
		ImageView picture;
		Bitmap mutableBitmap, mBitmap;
		Canvas c ;
		Paint p ;
		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_innitialvaluepic);
			db = new myDBHelper(Innitialvaluepic.this);
			
			listApIn = (ListView) findViewById(R.id.listApIn);
			apnameinnitial = (EditText)findViewById(R.id.apnameinnitial);
			xposition = (EditText)findViewById(R.id.xpos);
			yposition = (EditText)findViewById(R.id.ypos);
			radius = (EditText)findViewById(R.id.rad);
			angle = (EditText)findViewById(R.id.ang);			
			btn_calculate = (Button) findViewById(R.id.calculate);	
	        btn_plansave = (Button) findViewById(R.id.planpicsave);			
			btn_marker = (Button) findViewById(R.id.makermap);
			btn_next = (Button) findViewById(R.id.nextdetail);
			picture = (ImageView) findViewById(R.id.pictureMap);
						
			// Load picture đã được chọn 
			res = getResources();			    
			//Get image's size
		    BitmapFactory.Options dimensions = new BitmapFactory.Options(); 
		    dimensions.inJustDecodeBounds = true;
		    mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.newmap, dimensions);
		    imgheight = dimensions.outHeight;
		    imgwidth =  dimensions.outWidth;		    
		    //cast from immutableBitmap to mutableBitmap to insert into Canvas 
		    Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.newmap );
		    mutableBitmap = bm.copy(Bitmap.Config.ARGB_8888, true);
		    c = new Canvas( mutableBitmap );	
		    picture.setImageBitmap( mutableBitmap );

			//Picture duoc chon khao sat là picture đang load ở Activity trước đó
			int mapId = Integer.parseInt(Innitialvaluepic.this.getIntent().getStringExtra("mapid"));
			
			// Khởi tạo đối tượng vẽ ảnh lên ImageView
			p = new Paint();
			p.setAntiAlias(true);				
			
			//Load danh sách các AP thuộc mapId cần khảo sát
			//Khởi tạo dữ liệu cho mảng arr 
		    List<String> name = db.getAPName(mapId);
			final String []  arr = new String[name.size()]; 
		  	ArrayAdapter<String>adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name.toArray(arr));
		  	//Đưa Data source vào ListView
		  	listApIn.setAdapter(adapter);  	
			//Thiết lập sự kiện cho Listview 
		  	listApIn.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					 pos =  position;
					 // Lấy tên của AP trong vị trí được chọn
					 String item = parent.getAdapter().getItem(position).toString();
					 String[] splitItem = item.split(" ");
					 idAP = Integer.parseInt(splitItem[0]);
					 nameAP = splitItem[1];
					 apnameinnitial.setText(nameAP);
				  }}); 
		  	
		  	
		  	//Lấy toạ độ của AP cần khảo sát từ database
		  	String[] size = db.getAPpos(idAP);
		  	xinnitial = Float.parseFloat(size[0]);
		  	yinnitial = Float.parseFloat(size[1]);
		  	
			//Chọn toạ độ cần khảo sát
			picture.setOnTouchListener(new View.OnTouchListener()
			{
				 public boolean onTouch(View v,  MotionEvent event) {
				       // if(event.getAction() == MotionEvent.ACTION_UP) {
					 	int screenX = (int)event.getRawX();
		                int screenY = (int) event.getRawY();	                
		                
		                int[] posXY = new int[2];
		                v.getLocationOnScreen(posXY);
		                int x = posXY[0];
		                int y = posXY[1];
		                
		                int viewX = screenX - x;
		                int viewY = screenY - y;
				            
		                xposition.setText(Float.toString(viewX));
		                yposition.setText(Float.toString(viewY));					    
			            
			            Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.newmap );
					    mutableBitmap = bm.copy(Bitmap.Config.ARGB_8888, true);
					    p.setColor(Color.YELLOW);
					    c = new Canvas( mutableBitmap );
					    c.drawCircle(viewX, viewY , 3, p);
			            picture.setImageBitmap( mutableBitmap );
			            					
				        return true;				            				      
				    }}); 
			
			btn_marker.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {					
				    float x ;
				    float y;
				    x = Integer.parseInt(xposition.getText().toString());
				    y = Integer.parseInt(yposition.getText().toString());
				    //calculate the ratios between image's size and screen size
				   	p.setColor(Color.RED);
					Canvas cv = new Canvas(mutableBitmap);
					cv.drawCircle(x, y, 3, p);
					picture.setImageBitmap(mutableBitmap);
					
				}});
			
			//Tính các góc và khoảng cách từ các điểm khảo sát đến AP
			btn_calculate.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
						// luu giu gia tri toa do cua diem duoc chon khao sat
						float xtemp = Float.parseFloat(xposition.getText().toString());
						float ytemp = Float.parseFloat(yposition.getText().toString());
						// Khoảng cách từ điểm cần khảo sát đến AP	
			        	float dist1  = (float)Math.sqrt(Math.pow((xinnitial-xtemp),2) + Math.pow((yinnitial-ytemp),2));
			        	float dist2  = (float)Math.sqrt(Math.pow((xinnitial-xtemp),2) + Math.pow((yinnitial-yinnitial),2));
			        	float sinag = (dist2/dist1);			        	
			        	float ang = (float)(Math.asin(sinag));
			        	String L = String.valueOf(dist1);				        	
			        	radius.setText(L);
			        	String A = String.valueOf(ang);
			        	angle.setText(A);					
				}});
						
			//Luu vao database
			btn_plansave.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					db.addAPPlan(idAP, Float.parseFloat(radius.getText().toString()), Float.parseFloat(angle.getText().toString()),
								Float.parseFloat(xposition.getText().toString()), Float.parseFloat(yposition.getText().toString()));
				xposition.setText("");
				yposition.setText("");						
					
				}});
			
			btn_next.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// Giu lai trang thai load map ban dau khi chuyen sang activity khac 
					//String name = Innitialvalue.this.getIntent().getStringExtra("mapid");
					if( xposition.getText().toString().equals("") || yposition.getText().toString().equals("") )
						Toast.makeText( Innitialvaluepic.this, "Nhap day du toa do cua AP", Toast.LENGTH_SHORT).show();
					else{
						Intent intent = new Intent(Innitialvaluepic.this,WSTActivity.class);						
						intent.putExtra("APID", idAP);
						startActivity(intent);
					}
				}});									
			}
		
		@Override
		protected void onResume() {
	      super.onResume();
	      
	    }

		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// Inflate the menu; this adds items to the action bar if it is present.
//			getMenuInflater().inflate(R.menu.loadmap, menu);
			return true;
		}
	}

